package net.lab1024.smartdb.springboot.service;

import net.lab1024.smartdb.SmartDb;
import net.lab1024.smartdb.springboot.constants.UserLevelEnum;
import net.lab1024.smartdb.springboot.dao.SlaveUserDao;
import net.lab1024.smartdb.springboot.dao.UserMapper;
import net.lab1024.smartdb.springboot.domain.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author zhuoda
 */

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SmartDb smartDb;

    @Autowired
    private SlaveUserDao slaveUserDao;


    /**
     * 只需要在创建 “SmartDb”的时 设置支持spring <br>
     * SmartDbBuilder.setSmartDbExtEnum(SmartDbExtEnum.SPRING4) <br>
     * 则就可以支持Spring的事务
     *
     * @author : zhuoda
     */
    public List<UserEntity> test() {
        userMapper.delete(null);

        // 使用mybatis 插入master数据库
        UserEntity user = new UserEntity();
        user.setUsername("master_user_" + ThreadLocalRandom.current().nextInt(1000, 9999));
        user.setLevel(UserLevelEnum.VIP.name());
        user.setSex(1);
        user.setLoginTime(LocalDateTime.now());
        userMapper.insert(user);


        // 从master数据库将数据查出来，然后使用smartdb插入slave数据库
        List<UserEntity> userEntityList = userMapper.selectList(null);
        // 修改名字为slave
        userEntityList.forEach(e -> {
            e.setUsername(e.getUsername().replaceAll("master", "slave"));
        });
        //先删除
        smartDb.deleteSqlBuilder().table(UserEntity.class).execute();
        smartDb.batchInsert(userEntityList);

        // 使用smartdb从第二个数据库查出来，返回前端
        return slaveUserDao.selectUser();
    }

}
